import {getToken, getUuid} from '@/util/auth.js'
import {msg} from '@/util/util.js'



/**
 *   1. baseURL 测试环境
 * 	 2. apiURL  线上环境
 */

const baseURL  = 'http://192.168.3.163:9001'   
const apiURL = 'http://192.168.3.163:9001'  


/**
 * 
 * @param {接口请求地址} url 
 * @param {接口请求类型} method 
 * @param {接口请求参数} date 
 * @param {接口请求头的携带信息，如不自定将某人携带token为请求头部} header 
 * @param (status === 0 为接口请求失败返回失败原因，并弹框展示) 
 * @param (status === 1 为接口请求成功返回成功响应数据) 
 * @param (status === 2 为接口请求成功，但是需要token校验，没有token返回登录页面重新授权登录回去token)
 *
 *
 */

// 未获取token跳转的授权页面
const loginPage = 'pages/login/index'

// 接口请求提示语句
const message = '加载中...'


   
const request = ( url, method, date) => {
	var that = this
	var header = {
		'Content-type': 'application/json'
	}
	var pages = getCurrentPages();
	let currentRoute  = pages[pages.length-1].route;
	console.log("当前页面是" + currentRoute)
	console.log("token" + getToken())
	if (!getToken() && currentRoute != loginPage) {
		uni.showToast({
			icon:'error',
			title: "请先登录",
			duration: 2000
		});
		setTimeout(() => {
			uni.navigateTo({url: "/pages/login/index"});
		}, 2000);
		return;
	}
	header['Authorization'] = getToken()
	if (getUuid()) {
		header['Authorization'] = getUuid()
	}
    return new Promise((resolve, reject) => {
		uni.showLoading({
		    title: message
		});
        uni.request({
            method: method,
            url: baseURL + url,
            data: method == 'POST' ? JSON.stringify(date) : date,
            header: header,
            dataType: 'json'         
        }).then((response) => {
			uni.hideLoading();
			console.log(response);
			var res = response[1].data;
			 if (res.code == 40004) {
				uni.showToast({
				    title: '令牌失效，请登录',
					icon: 'error',
				    duration: 2000,
					success: () => {
						setTimeout(function () {
							uni.navigateTo({
								url: loginPage
							})
						}, 2000);
					}
				});
			} else if (res.code == 40003) {
				uni.showToast({
				    title: '令牌过期，请刷新',
					icon: 'error',
				    duration: 2000,
					success: () => {
						setTimeout(function () {
							uni.navigateTo({
								url: loginPage
							})
						}, 2000);
					}
				});
			} else {
				resolve(res);
			}
        }).catch(error => {
			uni.hideLoading();
            let [err, res] = error;
            reject(err)
			console.log(error[1].data)
			uni.showToast({
			    title: error,
				icon: 'none',
			    duration: 2000
			});
        })
    });
	
}
export default request